package com.bbzn.device.client.service.emq.data;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbzn.device.client.dataobject.FenceDevice;
import com.bbzn.device.client.service.EmqStrategy;
import com.bbzn.device.client.service.FenceDeviceService;
import com.bbzn.device.client.utils.OptionalBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.Timestamp;

/**
 * @Author: wulongbo
 * @Date : 2021/4/9 11:16
 * @Version 1.0
 */
@Slf4j
@Component
public class EmqFenceBindStrategy implements EmqStrategy {

    @Resource
    private FenceDeviceService fenceDeviceService;

    @Override
    public String emqAction(String payLoad) {
        try {
            JSONObject jsonObject = JSON.parseObject(payLoad);
            String imei = jsonObject.getString("imei");
            if(!OptionalBean.ofNullable(imei).isPresent()){
                return "json解析错误";
            }

            Long fenceId = jsonObject.getLong("fenceId");
            if(!OptionalBean.ofNullable(fenceId).isPresent()){
                return "json解析错误";
            }

            Long fenceDeviceId = jsonObject.getLong("fenceDeviceId");
            if(!OptionalBean.ofNullable(fenceDeviceId).isPresent()){
                return "json解析错误";
            }
            FenceDevice fenceDevice = new FenceDevice();
            fenceDevice.setId(fenceDeviceId);
            fenceDevice.setFenceId(fenceId);
            fenceDevice.setImei(imei);
            fenceDevice.setState(0);
            fenceDevice.setSetStatus(2);
            fenceDevice.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            fenceDeviceService.recordJob(fenceDevice);
        } catch (Exception e) {
            return "犯人绑定围栏失败！";
        }
        return "犯人绑定围栏成功！";
    }
}
